<template>
  <div class="login-wrap">
    <el-form
      label-position="left"
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="0px"
      class="login-container"
      v-if="ispwd && rememberp" 
    >
      <h3 class="title">{{  ruleForm.type ==1?'Gwhale卡-用户登录':'Gwhale卡-IAM登录' }}</h3> 
      <el-form-item prop="username" key="username">
        <el-input
          type="text"
          v-model="ruleForm.username"
          auto-complete="off"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password" key="password555">
        <!-- type="password" -->
        <!-- key="password" -->
        <!-- {{ encryptp(ruleForm.password) }} -->
        <el-input 
          v-model="ruleForm.password"
          auto-complete="off"
          placeholder="密码"
          show-password  
           pattern="[0-9]*"
           type="number" 
           clearable
        ></el-input>  
        <!-- :name="randomName" 
          :id="randomId"
          inputmode="none"  -->
      </el-form-item>

      <el-form-item prop="authType" key="authType">
        <el-radio-group v-model="ruleForm.authType" @input="authTypeChange">
          <!-- <el-radio label="0">手机号验证</el-radio> -->
          <el-radio label="1">谷歌验证</el-radio>
          <el-radio label="2">邮箱验证</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item prop="mobile" key="mobile" v-if="ruleForm.authType == 0">
        <el-input
          v-model="ruleForm.mobile"
          auto-complete="off"
          placeholder="手机号"
        ></el-input>
      </el-form-item>  
       <el-row v-if="ruleForm.authType == 0">
        <el-col :span="16">
          <el-form-item prop="code" key="code">
            <el-input
              type="text"
              v-model="ruleForm.code"
              auto-complete="off"
              placeholder="短信验证码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="code-box">
          <el-button
            type="primary"
            @click="getCode()"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `重新发送(${countdown})` : "获取验证码" }}
          </el-button>
        </el-col>
      </el-row> -->
      <el-form-item prop="code" key="code1" v-if="ruleForm.authType == 1">
        <el-input
          type="text"
          v-model="ruleForm.code"
          auto-complete="off"
          placeholder="谷歌验证码"
        ></el-input>
      </el-form-item>
      <el-form-item prop="email" key="email2" v-if="ruleForm.authType == 2">
        <el-input
          v-model="ruleForm.email"
          auto-complete="off"
          placeholder="邮箱"
        ></el-input>
      </el-form-item>
      <el-row v-if="ruleForm.authType == 2">
        <el-col :span="16">
          <el-form-item prop="code" key="code2">
            <el-input
              type="text"
              v-model="ruleForm.code"
              auto-complete="off"
              placeholder="邮箱验证码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="code-box">
          <el-button
            type="primary"
            @click="getCodeEm()"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `重新发送(${countdown})` : "获取验证码" }}
          </el-button>
        </el-col>
      </el-row>

      <el-row type="flex" justify="space-between">
        <el-col :span="10">
          <el-checkbox class="remember" v-model="ruleForm.rememberMe">
            30天免验证
          </el-checkbox>
        </el-col>
        <el-col :span="8" class="font14 aline-r pointer">
          <span class="text-poper" @click="changLogin">忘记密码</span> 
          <span style="color:red" @click="refresh">清除缓存</span>

        </el-col>
      </el-row>

      <el-form-item style="width: 100%">
        <el-button
          type="primary"
          style="width: 100%"
          @click="submitForm('ruleForm')"
          :loading="logining"
          >登录</el-button
        >
        <div class="otherLogin">
          其他登录方式：<label @click="changeUser" >{{  loginTypeTxt }}用户</label>
          
        </div>
      </el-form-item>
    </el-form>

    <el-form
      label-position="left"
      :model="ruleForm"
      :rules="rulesN"
      ref="ruleForm"
      label-width="0px"
      class="login-container"
      v-if="!rememberp"
    >
      <!-- <h3 class="title">用户登录</h3> -->
      <h3 class="title">{{  ruleForm.type ==1?'用户登录':'IAM登录' }}</h3>
      <el-form-item prop="username" key="username">
        <el-input
          type="text"
          v-model="ruleForm.username"
          auto-complete="off"
          placeholder="用户名"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password" key="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          auto-complete="off"
          placeholder="密码"  
          pattern="[0-9]*"
          show-password
        ></el-input>
        <!-- :name="randomName" 
          :id="randomId"
          inputmode="none"  -->
      </el-form-item>

      <el-row type="flex" justify="space-between">
        <el-col :span="10">
          <el-checkbox class="remember" v-model="ruleForm.rememberMe">
            30天免验证
          </el-checkbox>
        </el-col>
        <el-col :span="8" class="font14 aline-r pointer">
          <span class="text-poper" @click="changLogin">忘记密码</span>
          <span style="color: red;" @click="refresh">清除缓存</span>
        </el-col>
      </el-row>

      <el-form-item style="width: 100%">
        <el-button
          type="primary"
          style="width: 100%"
          @click="submitFormN('ruleForm')"
          :loading="logining"
          >登录</el-button
        >
        
      </el-form-item>
       <div class="otherLogin">  其他登录方式：<label @click="changeUser" >{{  loginTypeTxt }}用户</label>
        </div>
    </el-form>

    <el-form
      label-position="left"
      :model="resetForm"
      :rules="resetRules"
      ref="resetForm"
      label-width="0px"
      class="login-container"
      v-if="!ispwd"
    >
      <h3 class="title">找回密码</h3>
      <el-form-item prop="username" key="username1">
        <el-input
          type="text"
          v-model="resetForm.username"
          auto-complete="off"
          placeholder="用户名"
        ></el-input>
      </el-form-item> 
      <el-form-item prop="password"   key="password"> 
        <el-input 
          v-model="resetForm.password" 
          placeholder="新密码"
          name="password" 
          type="password"
          show-password 
          auto-complete="off"
        ></el-input> 
      </el-form-item>
      <el-form-item prop="authType" key="authType2">
        <el-radio-group v-model="resetForm.authType" @input="authTypeChange">
          <el-radio label="0">手机号验证</el-radio>
          <el-radio label="2">邮箱验证</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="mobile" key="mobile1" v-if="resetForm.authType == 0">
        <el-input
          v-model="resetForm.mobile"
          auto-complete="off"
          placeholder="手机号"
        ></el-input>
      </el-form-item>
      <!-- <el-row v-if="resetForm.authType == 0">
        <el-col :span="16">
          <el-form-item prop="code" key="code1">
            <el-input
              type="text"
              v-model="resetForm.code"
              auto-complete="off"
              placeholder="短信验证码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="code-box">
          <el-button
            type="primary"
            @click="getCode()"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `重新发送(${countdown})` : "获取验证码" }}
          </el-button>
        </el-col>
      </el-row> -->

      <el-form-item prop="email" key="email3" v-if="resetForm.authType == 2">
        <el-input
          v-model="resetForm.email"
          auto-complete="off"
          placeholder="邮箱"
        ></el-input>
      </el-form-item>
      <el-row v-if="resetForm.authType == 2">
        <el-col :span="16">
          <el-form-item prop="code" key="code4">
            <el-input
              type="text"
              v-model="resetForm.code"
              auto-complete="off"
              placeholder="邮箱验证码"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="code-box">
          <el-button
            type="primary"
            @click="getCodeEm()"
            :disabled="countdown > 0"
          >
            {{ countdown > 0 ? `重新发送(${countdown})` : "获取验证码" }}
          </el-button>
        </el-col>
      </el-row>

      <div class="font14 aline-r pointer margin-b10">
        <span class="text-poper" @click="changLogin">
          登录 <i class="el-icon-right"></i>
        </span>
      </div> 

      <el-form-item style="width: 100%">
        <el-button
          type="primary"
          style="width: 100%"
          @click="submitRForm('resetForm')"
          :loading="logining"
          >重置密码</el-button
        >
      </el-form-item>
    </el-form>

    <el-button class="register" type="danger" @click="reg()">
      立即注册
    </el-button>
  </div>
</template>
<script type="text/ecmascript-6">
import {
  setStore,
  getStore,
  removeStore,
  setStoreS,
  insertCharacter,
  phoneReg,
  emailReg,
} from "../utils/util";
import {
  req,
  reqJson,
  encrypt,
  encryptp,
  decryptp,
  getUrl,
} from "../api/axiosFun";
import FingerprintJS from "@fingerprintjs/fingerprintjs";
 
import axios from 'axios';
export default {
  name: "login",
  data() {
    return {
      randomName: 'password_' + Math.random().toString(36).substr(2, 9),
      randomId: 'password_' + Math.random().toString(36).substr(2, 9),
      logining: false,
      ispwd: true,
      countdown: 0,
      rememberp: true,
      loginTypeTxt:"IAM",
      ruleForm: {
        username: "",
        password: "",
        code: "",
        mobile: "",
        type: 1,
        authType: "1",
        rememberMe: false,
        email: "",
        deviceInfo: "",
      },
      obj: "",
      resetForm: {
        username: "",
        password: "",
        code: "",
        authType: "1",
        mobile: "",
        type: 1,
        email: "",
      },
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: phoneReg,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: emailReg,
            message: "请输入正确的邮箱",
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            pattern: /^\d{6}$/,
            message: "请输入正确的验证码",
            trigger: "blur",
          },
        ],
      },
      rulesN: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      resetRules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [
          { required: true, message: "请输入新密码", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: phoneReg,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      uuid:''
    };
  },
  created() {  
    FingerprintJS.load().then((fp) => {
      fp.get().then((result) => {
        this.ruleForm.deviceInfo = result.visitorId;
      });
    });

    let obj22 = getStore("ThObj"); 
    if (obj22) {
      this.obj =decryptp(JSON.parse(obj22).ThObj);  
    } 
   
    if (this.obj) {
      this.obj = JSON.parse(this.obj);
      this.ruleForm.username = this.obj.username;
      // this.ruleForm.password = this.obj.password;
      this.ruleForm.password = ''; 
      this.ruleForm.rememberMe = this.obj.rememberMe;
      this.ruleForm.authType = this.obj.authType || 1;
      this.obj.type == 1 ? (this.rememberp = false) : "";
      this.rememberp = false;
    }
    this.ruleForm.password = ''; 
  },
  methods: {
    changeUser(){ //切换账号  
      this.rememberp = true;
      if(this.ruleForm.type == 1){
        this.loginTypeTxt = '会员'
        this.ruleForm.type = 2
      }else{
        this.loginTypeTxt = 'IAM'
        this.ruleForm.type = 1
      } 
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.logining = true;
          let pamars = JSON.stringify(this.ruleForm);
          pamars = JSON.parse(pamars); 
          pamars.password = encrypt(pamars.password); 
          reqJson("post", "/jwt/login",  {
            ...pamars,
            uuid:this.uuid || '1233444'
          })
            .then((res) => {
              this.logining = false;  
              if (res.code == 0) { 
                let s_token = res.data.access_token
                  // l_token = res.data.refresh_token;
                setStoreS("ssttkktt", insertCharacter(s_token));
                // setStoreS("l_token", insertCharacter(l_token));
                if (pamars.rememberMe) {
                  let ThObj = {
                    // username: encryptp(this.ruleForm.username),
                    username:this.ruleForm.username, 
                    // password: encryptp(this.ruleForm.password),
                    rememberMe: true,
                    authType: this.ruleForm.authType,
                    type: this.ruleForm.type,
                  };
                  setStore("ThObj",{
                    ThObj:encryptp(JSON.stringify(ThObj)),
                  });
                }
                this.getInfo();
              } else {
                this.$message.error(res.msg);
                return;
              }
            })
            .catch((err) => {
              this.logining = false;
              this.$message.error(err);
            });
        } else {
          this.logining = false;
          return false;
        }
      });
    },
    submitFormN(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.logining = true;
          let pamars = JSON.stringify(this.ruleForm);
          pamars = JSON.parse(pamars);

          pamars.password = encrypt(pamars.password);

          reqJson("post", "/jwt/fastLogin", pamars)
            .then((res) => {
              this.logining = false;
              if (res.code == 0) {
                let s_token = res.data.access_token;
                  // l_token = res.data.refresh_token;
                setStoreS("ssttkktt", insertCharacter(s_token));
                // setStoreS("l_token", insertCharacter(l_token));
                if (!pamars.rememberMe) {
                  removeStore("ThObj");
                }
                this.getInfo();
              } else if (res.code == 408) {
                this.rememberp = true;
                this.ruleForm.rememberMe = true;
                removeStore("ThObj");
                this.$message.error(res.msg);
              } else {
                this.$message.error(res.msg);
                return;
              }
            })
            .catch((err) => {
              this.logining = false;
              this.$message.error(err);
            });
        } else {
          this.logining = false;
          return false;
        }
      });
    },
    submitRForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.logining = true;
          let pamars = JSON.stringify(this.resetForm);
          pamars = JSON.parse(pamars);
          pamars.password = encrypt(pamars.password);
          pamars.uuid = this.uuid  || '1233444';
          let url = getUrl(pamars); 
          reqJson("post", "/jwt/resetPwd" + url, {})
            .then((res) => {
              this.logining = false;
              if (res.code == 0) {
                this.$message.success("密码重置成功，请重新登录账号");
                this.changLogin();
              } else {
                this.$message.error(res.msg);
                return;
              }
            })
            .catch((err) => {
              this.logining = false;
              this.$message.error(err);
            });
        } else {
          this.logining = false;
          return false;
        }
      });
    },
    getInfo() { 
      req("get", "/api/photon/getUserInfo", {})
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            this.$router.push({ path: "/wallet" });
            this.logining = false;
            this.$store.commit("user", JSON.stringify(res.data));
          } else {
            this.$message({
              type: "info",
              message: res.msg,
            });
          }
        })
        .catch((err) => {});
    },
    getCode() {
      let myreg = phoneReg;
      let url = "";
      let params = {
        mobile: this.ruleForm.mobile,
        type: 1,
      };
      if (this.ispwd) {
        if (!this.ruleForm.mobile || !myreg.test(this.ruleForm.mobile)) {
          this.$message.error("请输入有效的手机号");
          return;
        }
        if (/^1[3-9]\d{9}$/.test(this.ruleForm.mobile)) {
          params.type = 0;
        }
        url = getUrl(params);
      } else {
        if (!this.resetForm.mobile || !myreg.test(this.resetForm.mobile)) {
          this.$message.error("请输入有效的手机号");
          return;
        }
        params.mobile = this.resetForm.mobile;
        if (/^1[3-9]\d{9}$/.test(this.resetForm.mobile)) {
          params.type = 0;
        }
        url = getUrl(params);
      }

      this.countdown = 60;
      reqJson("post", "/jwt/sms" + url, {}).then((res) => {
        if (res.code == 0) {
          this.$message.success("短信已发送，请注意查收");
          this.countdown = 60;
          this.uuid = res.data.uuid;
          let intervalId = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
            } else {
              clearInterval(intervalId);
            }
          }, 1000);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    getCodeEm() {
      let myreg = emailReg;
      let url = "";
      let params = {
        email: this.ruleForm.email,
      };
      if (this.ispwd) {
        if (!this.ruleForm.email || !myreg.test(this.ruleForm.email)) {
          this.$message.error("请输入有效的邮箱");
          return;
        }
      } else {
        if (!this.resetForm.email || !myreg.test(this.resetForm.email)) {
          this.$message.error("请输入有效的邮箱");
          return;
        }
        params.email = this.resetForm.email;
      }

      url = getUrl(params);
      this.countdown = 60;
      reqJson("post", "/jwt/sendEmail" + url, {}).then((res) => {
        if (res.code == 0) {
          this.$message.success("邮件已发送，请注意查收");
          this.countdown = 60;
          this.uuid = res.data.uuid;
          let intervalId = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
            } else {
              clearInterval(intervalId);
            }
          }, 1000);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    changLogin() {
      this.ispwd = !this.ispwd;
      this.countdown = 0;
      this.ruleForm = {
        username: "",
        password: "",
        code: "",
        mobile: "",
        type: 1,
        authType: "0",
        rememberMe: false,
        email: "",
      };
      this.resetForm = {
        username: "",
        password: "",
        code: "",
        authType: "0",
        mobile: "",
        type: 1,
        email: "",
      };
    },
    reg() {
      this.$router.push({ path: "/register" });
    },
    authTypeChange(e) {
      this.countdown = 0;
      this.ruleForm.mobile = "";
      this.ruleForm.code = "";
      this.ruleForm.email = "";
      this.resetForm.mobile = "";
      this.resetForm.code = "";
      this.resetForm.email = "";
    },
    refresh() { 
      localStorage.clear();
      sessionStorage.clear();
    },
  },
};
</script>

<style scoped>
.login-wrap {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  /* background-image: url(~@/assets/img/login_bg.png); */
  background-image: url(~@/assets/img/login_bg34.png); 
  background-repeat: no-repeat;
  background-position: top right;
  background-size: 100%;
  /* opacity: 0.8; */
}
.login-container {
  position: absolute;
  top: 300px;
  right: 270px;
  border-radius: 10px;
  width: 350px;
  padding: 30px 35px 15px 35px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 20px 2px rgba(0, 0, 0, 0.1);
}
.title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}
.remember {
  margin: 0px 0px 35px 0px;
}
.code-box {
  text-align: right;
}
.register {
  position: absolute;
  left: 402px;
  bottom: 200px;
}
.otherLogin{
  color: #505458; 
}
.otherLogin label:hover{
  color: #e3b85a;
  cursor: pointer;
}
.text-poper{
  color: #e3b85a;
}
</style>